package com.jie.lipassword;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.jie.lipassword.db.DbContect;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class AddActivity extends AppCompatActivity{
    private RelativeLayout add_type_title;
    private EditText type_name;
    private Button type_add_btn;

    DbContect helper;
    private SQLiteDatabase db;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_type);
        dbcontext();
        set_init();
    }

    private void set_init() {
        add_type_title = findViewById(R.id.add_type_title);
        FindTitle.setTitle(this,add_type_title,true,false,"添加类别");
        type_name = findViewById(R.id.type_name);
        type_add_btn = findViewById(R.id.type_add_btn);
        type_add_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String temp_type = type_name.getText().toString();
                if (temp_type == ""){

                }else {
                    //查找是否存在
                    Cursor cursor = db.query("TypeTable",null,"type_name=?",new String[]{temp_type},null,null,null);
                    while(cursor.moveToNext()){
                        @SuppressLint("Range") String id = cursor.getString(cursor.getColumnIndex("id"));
                        @SuppressLint("Range") String type_name = cursor.getString(cursor.getColumnIndex("type_name"));
                        Log.i("Mainactivity","result: id="  + id +" type_name: " + type_name);
                    }
                    if (cursor != null && cursor.moveToFirst()){
                        //存在
                        Toast.makeText(view.getContext(), "分类名已存在", Toast.LENGTH_SHORT).show();
                        // 关闭游标，释放资源
                        cursor.close();
                    }else{
                        //不存在
                        ContentValues values = new ContentValues();
                        values.put("type_name",temp_type);
                        db.insert("TypeTable",null,values);
                        // 关闭游标，释放资源
                        cursor.close();

                        finish();
                    }
                };

            }
        });
    }

    private void dbcontext(){
        helper = new DbContect(this);
        db = helper.getWritableDatabase();
    }
}
